#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
	
#include "joy.h"
	
static int joystick_fd = -1;

/* Abro el dispositivo */	
int open_joystick(){
	joystick_fd = open("/dev/input/js0", O_RDONLY | O_NONBLOCK);
	        if (joystick_fd < 0){
	                return joystick_fd;
		}	

	        return joystick_fd;
}
	
/* Lectura del dispositivo 
	@return 0 o -1 si hay un error
	@return 1 exito	
*/
int read_joystick_event(struct js_event *jse){
	int bytes;
	
	bytes = read(joystick_fd, jse, sizeof(*jse)); 
	if (bytes == -1){
		return 0;
	}
	
	if (bytes == sizeof(*jse)){
		return 1;
	}
	
	printf("Unexpected bytes from joystick:%d\n", bytes);
	
	        return -1;
}

/* Cierro el dispositivo */
	
void close_joystick(){
	close(joystick_fd);
}
	
int get_joystick_status(struct wwvi_js_event *wjse){
        int rc;
        struct js_event jse;
        if (joystick_fd < 0)
                return -1;
	
        while ((rc = read_joystick_event(&jse) == 1)) {
                jse.type &= ~JS_EVENT_INIT; /* ignore synthetic events */
                if (jse.type == JS_EVENT_AXIS) {
                        switch (jse.number) {
                        case 0: wjse->stick_x = jse.value;
                                break;
                        case 1: wjse->stick_y = jse.value;
                                break;
                        default:
                                break;
	                }
		} else if (jse.type == JS_EVENT_BUTTON) {
                        if (jse.number < 10) {
                                switch (jse.value) {
	                                case 0:
	                                case 1: wjse->button[jse.number] = jse.value;
	                                        break;
	                                default:
	                                        break;
	                        }
	                }
	        }
	}
        // printf("%d\n", wjse->stick1_y);
        return 0;
}

	/*
int main(int argc, char *argv[])
{
	int fd, rc;
	int done = 0;
	
	struct js_event jse;
	
	fd = open_joystick();
	if (fd < 0) {
		printf("open failed.\n");
	        exit(1);
	}
	
	while (!done) {
		rc = read_joystick_event(&jse);
		usleep(1000);
		if (rc == 1) {
		        printf("Event: time %8u, value %8hd, type: %3u, axis/button: %u\n", 
		        jse.time, jse.value, jse.type, jse.number);
	        }
	}
}*/
	
